/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xcjw.com.ui;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.xcjw.com.Base.StackManager;
import com.xcjw.com.Hy.DemoHelper;
import com.xcjw.com.R;
import com.xcjw.com.Utils.KeyboardUtils;
import com.xcjw.com.Utils.ToastUtil;
import com.xcjw.com.View.CustomDialog;



public class AddContactActivity extends BaseActivity {
      private EditText editText;
      private RelativeLayout searchedUserLayout;
      private TextView nameText;
      private Button searchBtn;
      private String toAddUsername;
      private ProgressDialog progressDialog;
      private CustomDialog dialog;
      private CustomDialog dialog4;
      private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                  switch (msg.what) {
                        case 0:
                              showiosDialog4();
                              break;
                  }
            }
      };

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.em_activity_add_contact);
            TextView mTextView = (TextView) findViewById(R.id.add_list_friends);
            dialog = new CustomDialog(this, R.style.customDialog, R.layout.ios_dialog);
            StackManager.getInstance().pushActivity(this);

            editText = (EditText) findViewById(R.id.edit_note);
            String strAdd = getResources().getString(R.string.add_friend);
            mTextView.setText(strAdd);
            String strUserName = "请输入手机号，搜索好友";
            editText.setHint(strUserName);
            dialog4 = new CustomDialog(this, R.style.customDialog, R.layout.ios_dialog4);
            searchedUserLayout = (RelativeLayout) findViewById(R.id.ll_user);
            nameText = (TextView) findViewById(R.id.name);
            searchBtn = (Button) findViewById(R.id.search);
      }


      /**
       * search contact
       *
       * @param v
       */
      public void searchContact(View v) {
            final String name = editText.getText().toString().toLowerCase();
            String saveText = searchBtn.getText().toString();
            if (getString(R.string.button_search).equals(saveText)) {
                  toAddUsername = name;
                  if (TextUtils.isEmpty(name)) {
                        ToastUtil.showToast("手机号不能为空");
                        KeyboardUtils.hideKeyboard(editText);
                        return;
                  }
                  if (!com.xcjw.com.Utils.Utils.isPhone(name)) {
                        ToastUtil.showToast("请输入手机号搜索");
                        return;
                  }
                  // TODO you can search the user from your app server here.
                  //show the userame and add button if user exist
                  searchedUserLayout.setVisibility(View.VISIBLE);
                  nameText.setText(toAddUsername);

            }
      }

      private void showiosDialog(String s) {
            if (dialog != null && dialog.isShowing()) {
                  dialog.dismiss();
            }
            dialog.show();
            TextView tvOk = (TextView) dialog.findViewById(R.id.ok);
            final TextView signs = (TextView) dialog.findViewById(R.id.textsign);
            signs.setText(s);
            tvOk.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                        dialog.dismiss();
                  }
            });
            dialog.show();
      }

      private void showiosDialog4() {
            if (dialog4 != null && dialog4.isShowing()) {
                  dialog4.dismiss();
            }
            dialog4.show();
            TextView tvOk = (TextView) dialog4.findViewById(R.id.tv_bind);
            TextView tvcan = (TextView) dialog4.findViewById(R.id.tv_cancl);
            final EditText signs = (EditText) dialog4.findViewById(R.id.textsign);
            tvOk.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {

                        new Thread(new Runnable() {
                              @Override
                              public void run() {
                                    try {
                                          EMClient.getInstance().contactManager().addContact(toAddUsername, signs.getText().toString());
                                    } catch (HyphenateException e) {
                                    }
                              }
                        }).start();

                        dialog4.dismiss();
                        progressDialog.dismiss();
                        String s1 = getResources().getString(R.string.send_successful);
                        Toast.makeText(getApplicationContext(), s1, Toast.LENGTH_SHORT).show();
                  }

            });


            tvcan.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                        dialog4.dismiss();
                  }
            });
            dialog4.show();
      }

      /**
       * add contact
       *
       * @param view
       */
      public void addContact(View view) {
            if (EMClient.getInstance().getCurrentUser().equals(nameText.getText().toString())) {
                  showiosDialog("不能添加自己为好友");
                  return;
            }

            if (DemoHelper.getInstance().getContactList().containsKey(nameText.getText().toString())) {
                  //let the user know the contact already in your contact list
                  if (EMClient.getInstance().contactManager().getBlackListUsernames().contains(nameText.getText().toString())) {
                        return;
                  }
                  showiosDialog(nameText.getText().toString() + "已经是你的好友了");
                  return;
            }

            progressDialog = new ProgressDialog(this);
            String stri = getResources().getString(R.string.Is_sending_a_request);
            progressDialog.setMessage(stri);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();

            new Thread(new Runnable() {
                  public void run() {
                        try {
                              //demo use a hardcode reason here, you need let user to input if you like
                              String s = getResources().getString(R.string.Add_a_friend);
                              handler.sendEmptyMessage(0);
                              //  showiosDialog4();
                              runOnUiThread(new Runnable() {
                                    public void run() {

                                    }
                              });
                        } catch (final Exception e) {
                              runOnUiThread(new Runnable() {
                                    public void run() {
                                          progressDialog.dismiss();
                                          String s2 = getResources().getString(R.string.Request_add_buddy_failure);
                                          //  Toast.makeText(getApplicationContext(), s2 + e.getMessage(), Toast.LENGTH_LONG).show();
                                    }
                              });
                        }
                  }
            }).start();
      }

      public void back(View v) {
            finish();
      }
}
